/**
 * Copyright © 2016 公司名. All rights reserved.
 * 
 * @Title: FrontUserServiceImpl.java
 * @Prject: LianniuWeb
 * @Package: com.lianniu.web.baseService.user.service.impl
 * @Description: TODO
 * @author: lzz
 * @date: 2016年8月4日 上午10:53:34
 * @version: V1.0
 */
package com.lianniu.web.baseService.user.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import com.lianniu.web.buyerProduct.service.IBuyerInfoService;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.lianniu.redis.RedisUtils;
import com.lianniu.web.base.BaseResult;
import com.lianniu.web.baseService.user.dao.IFrontUserDao;
import com.lianniu.web.baseService.user.dao.ISupplyDao;
import com.lianniu.web.baseService.user.dao.IUserLoginLogDao;
import com.lianniu.web.baseService.user.model.FrontUserVo;
import com.lianniu.web.baseService.user.model.Supply;
import com.lianniu.web.baseService.user.model.UserLoginLogVo;
import com.lianniu.web.baseService.user.service.IFrontUserService;
import com.lianniu.web.constants.ErrorCode;
import com.lianniu.web.constants.UserErrorCode;
import com.lianniu.web.util.MD5Util;
import com.lianniu.web.util.StringUtil;
import com.lianniu.web.util.UUIDUtil;

/**
 * @ClassName: FrontUserServiceImpl
 * @Description: TODO
 * @author: lzz
 * @date: 2016年8月4日 上午10:53:34
 */
@Service("frontUserService")
public class FrontUserServiceImpl implements IFrontUserService {
    private final static int TIME = 3600 * 24;
    @Resource
    private IFrontUserDao frontUserDao;
    @Resource
    private IUserLoginLogDao userLoginLogDao;

    @Autowired
    IBuyerInfoService buyerInfoService;

    @Resource
    private ISupplyDao supplyDao;

    private final static Logger logger = Logger.getLogger(FrontUserServiceImpl.class);

    public static final String TYPE_BUYER = "0";
    public static final String TYPE_SELLER = "1";
    public static final String TYPE_STAFF = "2";
    @Override
    @Transactional
    public BaseResult login(HttpServletRequest request, String username, String userpasswd,
                    String codeUuid, String code, int times,String type) {
        logger.info("login begin.");
        logger.info("parameter username:" + username);
        logger.info("parameter userpasswd:" + userpasswd);
        logger.info("parameter codeUuid:" + codeUuid);
        logger.info("parameter code:" + code);
        logger.info("parameter times:" + times);
        logger.info("login checkParameter begin.");
        if (StringUtil.isEmpty(username)) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                            ErrorCode.ParaCheckErrorRetInfo);
        }
        if (StringUtil.isEmpty(userpasswd)) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                            ErrorCode.ParaCheckErrorRetInfo);
        }
        if (StringUtil.isEmpty(codeUuid)) {
            return BaseResult.fail(ErrorCode.IsNullRetCode, ErrorCode.IsNullRetInfo);
        }
        if (times > 3) {

            if (StringUtil.isEmpty(code)) {
                return BaseResult.fail(ErrorCode.IsNullRetCode, ErrorCode.IsNullRetInfo);
            }

            if (!RedisUtils.get("codeUuid:" + codeUuid).equalsIgnoreCase(code)) {
                return BaseResult.fail(UserErrorCode.CaptchaErrorRetCode,
                                UserErrorCode.CaptchaErrorRetInfo);
            }
        }
        logger.info("login checkParameter end.");
        FrontUserVo frontUserVo = new FrontUserVo();
        frontUserVo.setUserName(username);
        logger.info("login getUser beigin.");
        List<FrontUserVo> list = frontUserDao.getUser(frontUserVo);
        FrontUserVo rtFrontUserVo = null;
        if (list == null || list.size() < 1) {
            return BaseResult.fail(UserErrorCode.UserNotExistErrorRetCode,
                            UserErrorCode.UserNotExistErrorRetInfo);
        } else {
            for(FrontUserVo fuv:list){
                if(fuv.getDelFlag().equals("1")){
                    rtFrontUserVo = fuv;
                }
            }
            logger.info("login getUser frontUserVo:" + JSON.toJSONString(rtFrontUserVo));
            logger.info("login getUser end.");
        }
        if(null == rtFrontUserVo){
            return BaseResult.fail(UserErrorCode.UserNotExistErrorRetCode,
                    UserErrorCode.UserNotExistErrorRetInfo);
        }
        logger.info("login checkuserpasswd begin.");
        if (!MD5Util.checkPassword(userpasswd, rtFrontUserVo.getLoginPassWord())
                        || !rtFrontUserVo.getUserName().equals(username)) {
            return BaseResult.fail(UserErrorCode.UserOrPassErrorRetCode,
                            UserErrorCode.UserOrPassErrorRetInfo);
        }
        Map<String, Object> result = new HashMap<String, Object>();
        /*if(!"1".equals(type)) {
            BaseResult buyer = buyerInfoService.getBuyerInfoByUserId(rtFrontUserVo.getUsersId().toString());
            if (buyer.getData() == null)
            {
                return BaseResult.fail("1003","用户没有权限");
            }
            result.put("buyer_userid", rtFrontUserVo.getUsersId());
        }
        if ("1".equals(type)){
            Supply supply = supplyDao.selectByUsersId(rtFrontUserVo.getUsersId().toString());
            if(supply == null)
            {
                return BaseResult.fail("1003","用户没有权限");
            }
            result.put("seller_userid", rtFrontUserVo.getUsersId());
        }*/
        logger.info("userCheckFail checkuserpasswd end.");
        String token = UUIDUtil.getUUID();
        RedisUtils.set("usrMgr:" + token, username);
        RedisUtils.set("usrMgr:" + username, token);
        RedisUtils.expire("usrMgr:" + token, TIME);
        RedisUtils.expire("usrMgr:" + username, TIME);
        result.put("token", token);
        result.put("username", rtFrontUserVo.getUserName());
        result.put("userid", rtFrontUserVo.getUsersId());
        result.put("user", rtFrontUserVo);
        result.put("userpasswd", userpasswd);
        logger.info("userCheckFail return:" + JSON.toJSONString(result));
        logger.info("login end.");
        logger.info("login addLog begin.");
        // 获取登陆用户IP地址
        String ip = request.getHeader("x-forwarded-for");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getHeader("WL-Proxy-Client-IP");
        }
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
            ip = request.getRemoteAddr();
        }
        // 构建登陆日志对象
        UserLoginLogVo userLoginLogVo = new UserLoginLogVo();
        userLoginLogVo.setLogInTime(new Date());
        userLoginLogVo.setLoginIp(ip);
        userLoginLogVo.setUserId(rtFrontUserVo.getUsersId());
        userLoginLogVo.setAddTime(userLoginLogVo.getLogInTime());
        userLoginLogDao.addUserLoginLog(userLoginLogVo);
        result.put("logId", userLoginLogVo.getId());
        logger.info("login addLog end.");
        return BaseResult.success(result);
    }

    @Override
    public BaseResult updatePwd(String username, String oldpasswd, String newpasswd,
                    String codeUuid, String code) {
        logger.info("updatePwd begin.");
        logger.info("parameter username:" + username);
        logger.info("parameter oldpasswd:" + oldpasswd);
        logger.info("parameter newpasswd:" + newpasswd);
        logger.info("parameter codeUuid:" + codeUuid);
        logger.info("updatePwd checkParameter begin.");
        if (StringUtil.isEmpty(username)) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                            ErrorCode.ParaCheckErrorRetInfo);
        }
        if (StringUtil.isEmpty(oldpasswd)) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                            ErrorCode.ParaCheckErrorRetInfo);
        }
        if (StringUtil.isEmpty(newpasswd)) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                            ErrorCode.ParaCheckErrorRetInfo);
        }
        if (StringUtil.isEmpty(codeUuid)) {
            return BaseResult.fail(UserErrorCode.CaptchaErrorRetCode, UserErrorCode.CaptchaErrorRetInfo);
        }
        if (!code.equalsIgnoreCase(RedisUtils.get("codeUuid:" + codeUuid))) {
            return BaseResult.fail(UserErrorCode.CaptchaErrorRetCode,
                            UserErrorCode.CaptchaErrorRetInfo);
        }
        logger.info("updatePwd checkParameter end.");
        FrontUserVo frontUserVo = new FrontUserVo();
        frontUserVo.setUserName(username);
        logger.info("updatePwd getUser beigin.");
        List<FrontUserVo> list = frontUserDao.getUser(frontUserVo);
        FrontUserVo rtFrontUserVo;
        if (list == null || list.size() < 1) {
            return BaseResult.fail(UserErrorCode.UserNotExistErrorRetCode,
                            UserErrorCode.UserNotExistErrorRetInfo);
        } else {
            rtFrontUserVo = list.get(0);
            logger.info("updatePwd getUser frontUserVo:" + JSON.toJSONString(rtFrontUserVo));
            logger.info("updatePwd getUser end.");
        }
        logger.info("updatePwd checkuserpasswd begin.");
        if (!MD5Util.checkPassword(oldpasswd, rtFrontUserVo.getLoginPassWord())
                        || !rtFrontUserVo.getUserName().equals(username)) {
            return BaseResult.fail(UserErrorCode.UserOrPassErrorRetCode,
                            UserErrorCode.UserOrPassErrorRetInfo);
        }
        logger.info("updatePwd checkuserpasswd end.");
        frontUserVo.setUsersId(rtFrontUserVo.getUsersId());
        frontUserVo.setLoginPassWord(MD5Util.getMD5String(newpasswd));
        logger.info("updatePwd updatePwdById begin.");
        Integer i = frontUserDao.updatePwdById(frontUserVo);
        logger.info("updatePwd updatePwdById end.");
        return BaseResult.success(i);
    }

    @Override
    public BaseResult insertFrontUser(FrontUserVo frontUserVo) {
        logger.info("insertFrontUser begin");
        logger.info("insertFrontUser: input data check begin");
        logger.info("insertFrontUser dictType:" + JSON.toJSONString(frontUserVo));
        BaseResult baseResult;
        if (StringUtil.isEmpty(frontUserVo.getMobile())) {

            baseResult = BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                            ErrorCode.ParaCheckErrorRetInfo);
            return baseResult;
        }
        if (StringUtil.isEmpty(frontUserVo.getLoginPassWord())) {

            baseResult = BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                            ErrorCode.ParaCheckErrorRetInfo);
            return baseResult;
        }
        logger.info("insertFrontUser: input data check end");
         FrontUserVo existUser = (FrontUserVo)this.getUserByUserName(frontUserVo.getUserName()).getData();
        if(existUser != null){
            existUser.setLoginPassWord(frontUserVo.getLoginPassWord());
            this.updatePassword(existUser);
            frontUserVo.setUsersId(existUser.getUsersId());
            return BaseResult.success(existUser);
        }
        return BaseResult.success(frontUserDao.addUser(frontUserVo));
    }

    @Override
    public boolean isExistMobile(String mobile,String supply) {
        logger.info("FrontUserServiceImpl isExistMobile begin.");
        logger.info("input data check begin.");
        if (StringUtil.isEmpty(mobile)) {
            return false;
        }
        logger.info("input data check end.");

        logger.info("isExistMobile begin.");
        boolean isExistFlg = frontUserDao.isExistMobile(mobile);
        if (!isExistFlg){
            return true;
        }
        FrontUserVo param = new FrontUserVo();
        param.setUserName(mobile);
        List<FrontUserVo> list = this.frontUserDao.getUser(param);
        FrontUserVo login = list.get(0);
        if(!"yes".equals(supply)){
            BaseResult buyer = buyerInfoService.getBuyerInfoByUserId(login.getUsersId().toString());
            if (buyer.getData() == null){
                return true;
            }
            return false;
        }else{
            Supply s = supplyDao.selectByUsersId(login.getUsersId().toString());
            if(s == null){
                return true;
            }
            return false;
        }
    }

    @Override
    public BaseResult forgetPwd(String username, String newpasswd, String codeUuid, String code) {
        logger.info("forgetPwd begin.");
        logger.info("parameter username:" + username);
        logger.info("parameter newpasswd:" + newpasswd);
        logger.info("parameter codeUuid:" + codeUuid);
        logger.info("forgetPwd checkParameter begin.");
        if (StringUtil.isEmpty(username)) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                            ErrorCode.ParaCheckErrorRetInfo);
        }
        if (StringUtil.isEmpty(newpasswd)) {
            return BaseResult.fail(ErrorCode.ParaCheckErrorRetCode,
                            ErrorCode.ParaCheckErrorRetInfo);
        }
        if (StringUtil.isEmpty(codeUuid)) {
            return BaseResult.fail(ErrorCode.IsNullRetCode, ErrorCode.IsNullRetInfo);
        }
        if (!RedisUtils.get("codeUuid:" + codeUuid).equalsIgnoreCase(code)) {
            return BaseResult.fail(UserErrorCode.CaptchaErrorRetCode,
                            UserErrorCode.CaptchaErrorRetInfo);
        }
        logger.info("forgetPwd checkParameter end.");
        FrontUserVo frontUserVo = new FrontUserVo();
        frontUserVo.setUserName(username);
        logger.info("forgetPwd getUser beigin.");
        List<FrontUserVo> list = frontUserDao.getUser(frontUserVo);
        FrontUserVo rtFrontUserVo;
        if (list == null || list.size() < 1) {
            return BaseResult.fail(UserErrorCode.UserNotExistErrorRetCode,
                            UserErrorCode.UserNotExistErrorRetInfo);
        } else {
            rtFrontUserVo = list.get(0);
            logger.info("forgetPwd getUser frontUserVo:" + JSON.toJSONString(rtFrontUserVo));
            logger.info("forgetPwd getUser end.");
        }
        rtFrontUserVo.setLoginPassWord(MD5Util.getMD5String(newpasswd));
        return updatePassword(rtFrontUserVo);
    }

    @Override
    public BaseResult updatePassword(FrontUserVo frontUserVo){
        FrontUserVo param = new FrontUserVo();
        param.setUsersId(frontUserVo.getUsersId());
        param.setLoginPassWord(frontUserVo.getLoginPassWord());
        logger.info("forgetPwd updatePwdById begin.");
        Integer i = frontUserDao.updatePwdById(frontUserVo);
        return BaseResult.success(i);
    }
    @Override
    public BaseResult getFrontUserId(String id) {
        Supply s = frontUserDao.getUserById(id);
        return BaseResult.success(s);
    }

    @Override
    public BaseResult getUser(String userId) {
        FrontUserVo frontUserVo = new FrontUserVo();
        frontUserVo.setUsersId(Long.valueOf(userId));
        return BaseResult.success(this.frontUserDao.getUser(frontUserVo));
    }
    @Override
    public BaseResult selectMobilAndId(String mobile) {
       logger.info("selectMobilAndId begin");
        return BaseResult.success(frontUserDao.selectMobilAndId(mobile));
    }
    @Override
    public BaseResult updateHeadById(FrontUserVo frontUserVo) {
		logger.info("updateHeadById begin");
	    logger.info("updateHeadById: update data check begin");
	    logger.info("updateSupplyById: update data check end");
		return BaseResult.success(frontUserDao.updateHeadById(frontUserVo));
	
	}

	@Override
	public BaseResult getPicById(String userId) {
		logger.info("getPicById begin");
		return BaseResult.success(frontUserDao.getPicById(userId));
	}

    @Override
    public BaseResult getUserByUserName(String userName) {
        FrontUserVo frontUserVo = new FrontUserVo();
        frontUserVo.setUserName(userName);
        List<FrontUserVo> result = this.frontUserDao.getUser(frontUserVo);
        if (result != null && result.size() >0) {
            return BaseResult.success(result.get(0));
        }
        return BaseResult.success();
    }

	@Override
	public BaseResult isLogin(HttpServletRequest request, String username,
			String userpasswd) {
//		String token = RedisUtils.get("usrMgr:" + username);
//		if (StringUtils.isNotEmpty(token)) {
			FrontUserVo frontUserVo = new FrontUserVo();
	        frontUserVo.setUserName(username);
	        List<FrontUserVo> result = this.frontUserDao.getUser(frontUserVo);
	        logger.info(result.size()+"===========返回的结果长度为。。。。。。。。。。。。。。。。。。。。。");
	        if (result != null && result.size() >0) {
	            return BaseResult.success(result.get(0));
	        }
//		}
		return null;
	}
}
